package com.rlz.base.util.single

/**
 * Created by RLZ
 * on 2021/10/15
 *
 * 带参数的单例类封装 T为实例化对象 P为可以传递
 */
open class Singleton<out T, in P> constructor(creator: (P) -> T) {

    private var mCreator: ((P) -> T)? = creator

    @Volatile
    private var mInstance: T? = null

    fun get() {
        get()
    }

    fun get(params: P): T {
        val instance = mInstance
        if (instance != null)
            return instance

        return synchronized(this) {
            val ins = mInstance
            if (ins != null) ins
            else {
                val created = mCreator!!(params)
                mInstance = created
                mCreator = null
                created
            }
        }
    }

}